#include "TCPClient.h"
#include <iostream>
#include "URI.h"

using namespace qy;

int main(int argc, char *argv[])
{
	if(argc != 2)
	{
		std::cout << "Usage: " << argv[0] << " url\n";
		return -1;
	}
	std::string url(argv[1]);
	if(url.find("http://") != 0)
	{
		url = "http://" + url;
	}
	URI u(url);
	if(u.fullPath().length() == 0)
	{
		std::cout << "Error url\n";
		return -1;
	}
	TCPClient *client = new TCPClient(u.host().c_str(), u.port() > 0 ? u.port() : 80);
	std::string host = u.host();
	if(u.port() > 0) 
	{
		host = host + "[";
		host += u.port();
		host += "]";
	}
	std::string requestLine = "GET " + u.fullPath() + " HTTP/1.1\r\nHost:"
	+ u.host()  + "\r\n\r\n";

	client->connect();
	int i = client->send(requestLine.c_str(), requestLine.length());
	
	char buffer[1025];
	int len = client->receive(buffer, 1024);
	while(len > 0)
	{
		buffer[len] = '\0';
		std::cout << buffer;
		len = client->receive(buffer, 1024);
	}
	return 0;
}
